// ==UserScript==
// @name         复制搜索词表格
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://sellercentral.amazon.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=amazon.com
// @updateURL    https://gitee.com/great-pacey/tampermonkey/raw/master/ABA.Search.user.js
// @grant        unsafeWindow
// @grant        GM_setClipboard
// @grant        GM_registerMenuCommand
// @grant        GM.setValue
// @grant        GM.getValue
// ==/UserScript==

(async function () {
    let testFlag = false
    let BRAND, Step, TIME, START, END, TOTALTIMES, READY = []
    let MAX_TIMES = testFlag ? 2 :30
    let INIT_TIMES = 0
    let ALL_TIMES = []
    let tableStr = ''
    let YEAR

    function reset() {
        BRAND = ''
        Step = ''
        TIME = ''
        START = ''
        END = ''
        TOTALTIMES = 0;
        READY = []
        MAX_TIMES = testFlag ? 2 :30
        INIT_TIMES = 0
        ALL_TIMES = []
        tableStr = ''
        YEAR = ''
    }

    GM_registerMenuCommand('抓取30期', async () => {
        reset()
        tableStr += genHeader() + '\n'
        INIT_TIMES = getCurrentTime()
        ALL_TIMES = getAllTimes()
        await loopAllTime()
    })

    GM_registerMenuCommand('抓取一期', async () => {
        reset()
        tableStr += genHeader() + '\n'
        getMetaData()
        await loopOneTime()
        GM_setClipboard(tableStr)
        alert('已复制，直接在表格上粘贴。抓取范围：' + ALL_TIMES[READY[0]] + '至' + ALL_TIMES[READY[READY.length - 1]])
    })

    // 切成 100 条每页
    async function changePerPage() {
        return new Promise(async resolve => {
            if (document.querySelectorAll('kat-dropdown')[3].shadowRoot.querySelector('.select-header').innerText.includes('100')) {
                await wait()
                resolve()
            } else {
                document.querySelectorAll('kat-dropdown')[3].shadowRoot.querySelector('.select-header').click()
                await wait()
                let length = document.querySelectorAll('kat-dropdown')[3].shadowRoot.querySelectorAll('kat-option').length
                document.querySelectorAll('kat-dropdown')[3].shadowRoot.querySelectorAll('kat-option')[length-1].click()
                await waitForData()
                resolve()
            }
        })
    }

    // 自动切换多期报告
    async function loopAllTime() {
        while(!TOTALTIMES || READY.length < Math.min(TOTALTIMES - INIT_TIMES, MAX_TIMES)) {
            await nextTimes()
            await changePerPage()
            await wait(1000)
            getMetaData()
            await loopOneTime()
            await wait(1000)
        }
        GM_setClipboard(tableStr)
        alert('已复制，直接在表格上粘贴。抓取范围：' + ALL_TIMES[READY[0]] + '至' + ALL_TIMES[READY[READY.length - 1]])
    }

    async function wait(num) {
        return new Promise(resolve => {
            setTimeout(resolve, num || 2000);
        })
    }

    // 翻页查找一期数据
    async function loopOneTime() {
        return new Promise(async resolve => {
            tableStr += await getData() + '\n'
            while(getCurrentPage() < (testFlag ? 2 :getTotalPage())) {
                await goNextPage()
                tableStr += await getData() + '\n'
            }
            resolve()
        })
    }

    function getAllTimes() {
        let dropdown = document.querySelectorAll('kat-dropdown')[2]
        let options = dropdown.shadowRoot.querySelectorAll('kat-option')
        return [].slice.call(options).map(i => i.innerText.trim())
    }

    function getCurrentTime() {
        let options = getAllTimes()
        let current = document.querySelectorAll('kat-dropdown')[2].shadowRoot.querySelector('.select-header').innerText
        return options.indexOf(current)
    }

    // 切换期数
    async function nextTimes() {
        return new Promise(resolve => {
            let dropdown = document.querySelectorAll('kat-dropdown')[2]
            dropdown.shadowRoot.querySelector('.indicator').click()
            setTimeout(async () => {
                let options = dropdown.shadowRoot.querySelectorAll('kat-option')
                TOTALTIMES = options.length
                for (let i = INIT_TIMES; i < TOTALTIMES; i++) {
                    if (READY.includes(i)) continue
                    READY.push(i)
                    options[i].click()
                    await wait(1500)
                    await apply()
                    await wait(2500)
                    resolve()
                    break
                }
            }, 1000)
        })
    }

    // 点应用按钮
    async function apply() {
        return new Promise(async resolve => {
            document.querySelector('kat-popover').querySelector('kat-button').shadowRoot.querySelector('button').click()
            await waitForData()
            resolve()
        })
    }

    // 等待至加载完成
    async function waitForData() {
        return new Promise(async resolve => {
            await wait()
            try {
                let length = document.querySelectorAll('tbody')[1].innerText.split('\n').length
                if (length >= 25) {
                    resolve()
                } else {
                    await wait(1000)
                    waitForData().then(resolve)
                }
            } catch (error) {
                await wait(1000)
                waitForData().then(resolve)
            }
        })
    }

    // 翻页
    async function goNextPage() {
        return new Promise(async resolve => {
            await wait(1000)
            document.querySelector('kat-pagination').shadowRoot.querySelector('ul.pages+span>kat-icon').click()
            await wait()
            resolve()
        })
    }

    function getCurrentPage() {
        return Number(document.querySelector('kat-input').shadowRoot.querySelector('input').value)
    }

    function getTotalPage() {
        return Number(document.querySelector('kat-input+span').innerText.slice(1))
    }

    function getMetaData() {
        BRAND = document.querySelectorAll('kat-dropdown')[0].shadowRoot.querySelector('div').innerText
        Step = document.querySelectorAll('kat-dropdown')[1].shadowRoot.querySelector('div').innerText
        let str = document.querySelectorAll('kat-dropdown')[2].shadowRoot.querySelector('div').innerText
        let arr = str.split(/\||,|\s\-\s/g).map(i => i.trim())
        TIME = arr[0]
        START = arr[1]
        END = arr[2]
        YEAR = arr[3]
    }

    function getData() {
        return new Promise(resolve => {
            function l() {
                try {
                    let tbodys = document.querySelectorAll('tbody')
                    let keywords = tbodys[0].innerText.split('\n')
                    let data = tbodys[1].innerText.split('\n').map((i, n) => {
                        let arr = i.split('\t').slice(1)
                        arr.unshift(keywords[n])
                        arr.unshift(END)
                        arr.unshift(START)
                        arr.unshift(TIME)
                        arr.unshift(YEAR)
                        arr.unshift(Step)
                        arr.unshift(BRAND)
                        return arr
                    })
                    resolve(data.map(i => i.join('\t')).join('\n'))
                } catch (error) {
                    setTimeout(l, 1500)
                }
            }
            l()
        })
    }

    function genHeader() {
        return ['品牌','时间跨度', '年份', '期数','起始日期','结束日期','关键词', '搜索量', '总展示量', '自展示量', '占有率', '总点击量', '自点击量', '占有率', '点击当日达', '总加购量', '自加购量', '占有率', '加购当日达', '总购买量', '自购买量', '占有率', '购买当日达'].join('\t')
    }

})()